<?php
namespace king;

/**
 * Created by PhpStorm.
 * User: seanwang
 * Date: 2017/11/19
 * Time: 上午10:53
 */
class geography
{
    //此处为高德开发配置key
    private $key = '66a6ceb5c02c3b17c8b5bae7948a5c27';

    /**
     * 坐标点距离计算
     */
    /***
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return int
     */
    public static function getDistance($lat1, $lng1,$lat2,$lng2)
    {
        $earthRadius = 6367000;//approximate radius of earth in meters


        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        //精确到米返回整型
        return intval($calculatedDistance);
    }

    //逆地理编码
    public function get_address($lat,$lng){
        $key = $this->key;
        $url = 'http://restapi.amap.com/v3/geocode/regeo?key='.$key.'&location='.$lng.','.$lat.'&radius=1000&extensions=all&batch=false&roadlevel=0';
        $data = $this->curl($url);
        $data = json_decode($data);
        if(!empty($data)){
            $addres_gd = $data->regeocode->formatted_address;
            if(empty($addres_gd)){
                $addres_gd = '未知地区';
            }
        }else{
            $addres_gd = '';
        }
        return $addres_gd;
    }

    //地理编码
    public function get_ll($address){
        $key = $this->key;
        $url = 'http://restapi.amap.com/v3/geocode/geo?address='.$address.'&key='.$key;
        $data = $this->curl($url);
        $data = json_decode($data);//location

        //判断用户输入地址是否存在
        if(!empty($data) && !empty($data->geocodes)){
            $location = $data->geocodes[0]->location;
        }else{
            $location = '';
        }
        return $location;
    }


    /***
     * @param $url
     * @return mixed
     */
    public function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}